package com.xiaolin.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaolin.admin.annotations.DataPerm;
import com.xiaolin.admin.constants.FlagConstant;
import com.xiaolin.admin.exception.ServiceException;
import com.xiaolin.admin.mapper.SysUserMapper;
import com.xiaolin.admin.mapper.SysUserRoleMapper;
import com.xiaolin.admin.model.dto.CurrentUser;
import com.xiaolin.admin.model.dto.SysUserView;
import com.xiaolin.admin.model.entity.SysUser;
import com.xiaolin.admin.model.entity.SysUserRole;
import com.xiaolin.admin.service.SysUserService;
import com.xiaolin.admin.utils.ContextUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author xiaolin
 * @since 2024-07-12
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private ContextUtil contextUtil;

    @DataPerm
    @Override
    public List<SysUserView> getUserList(SysUser user) {
        return userMapper.getUserList(user);
    }

    @DataPerm(argIndex = 2)
    @Override
    public PageInfo<SysUserView> getUserPage(Integer page, Integer pageSize, SysUser user) {
        PageHelper.startPage(page, pageSize);
        List<SysUserView> userList = userMapper.getUserList(user);
        return new PageInfo<>(userList);
    }

    /**
     * 校验用户唯一性
     *
     * @param user
     * @return
     */
    @Override
    public void checkUnique(SysUser user) {
        long count = userMapper.selectCount(new LambdaQueryWrapper<SysUser>()
                .and(qw -> qw.eq(SysUser::getUsername, user.getUsername()).or().eq(SysUser::getUserAccount, user.getUserAccount()))
                .ne(Objects.nonNull(user.getId()), SysUser::getId, user.getId()));
        if (count > 0) {
            ServiceException.error("用户名或账号重复了");
        }
    }

    @Override
    public void deleteRoleRelation(Integer userId) {
        CurrentUser user = contextUtil.getCurrentUser();
        userRoleMapper.update(new SysUserRole(), new UpdateWrapper<SysUserRole>().lambda()
                .set(SysUserRole::getFlag, FlagConstant.DELETED)
                .set(SysUserRole::getUpdator, user.getId())
                .eq(SysUserRole::getUserId, userId));
    }

    @Override
    public boolean addUser(SysUser user) {
        CurrentUser currentUser = contextUtil.getCurrentUser();
        // 校验用户唯一性
        checkUnique(user);
        // 密码 MD5 加密
        user.setUserPassword(DigestUtils.md5Hex(user.getUserPassword()));
        user.setCreator(currentUser.getId());
        user.setUpdator(currentUser.getId());
        userMapper.insert(user);
        return true;
    }

    @Override
    public SysUser getUser(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public boolean updateUser(SysUser user) {
        // 校验用户唯一性
        checkUnique(user);
        userMapper.updateById(user);
        return true;
    }

    @Override
    public boolean status(Integer id, String status) {
        CurrentUser user = contextUtil.getCurrentUser();
        userMapper.update(new SysUser(), new UpdateWrapper<SysUser>().lambda()
                .set(SysUser::getAvailable, status)
                .set(SysUser::getUpdator, user.getId())
                .eq(SysUser::getId, id));
        return true;
    }

    @Override
    public boolean deleteUser(Integer id) {
        // 删除用户与角色的关联关系
        deleteRoleRelation(id);
        userMapper.deleteById(id);
        return true;
    }
}
